package com.lagou.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer){
        this.clazz=clazz;
        this.serializer=serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int length = byteBuf.getInt(0);
        byte[] content = new byte[length];
        byteBuf.getBytes(4, content, 0, length);
        Object o = serializer.deserialize(clazz, content);
        byteBuf.skipBytes(byteBuf.readableBytes());
        list.add(o);
    }
}
